package org.nf.web.mapping;

import jakarta.servlet.http.HttpServletRequest;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.config.Configure;
import org.nf.web.servlet.Controller;
import org.nf.web.servlet.HandleMapping;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author czl
 * @Date 2024-05-14
 * 简单请求处理映射
 */
public class SimplerHandlerMapping implements HandleMapping {

    /**
     * 保存过滤好的Controller，key为请求的映射地址，value为Controller的Class对象
     */
    private Map<String,Class<?>> map = new HashMap<>();

    @Override
    public void init(Configure configure) {
        //获取所有扫描的class
        Set<Class<?>> classes = configure.getClasses();
        classes.forEach(clazz ->{
            //找出带有@RequestMapping注解的类型并收集起来
            if(clazz.isAnnotationPresent(RequestMapping.class)&& Controller.class.isAssignableFrom(clazz)){
                String uri = clazz.getAnnotation(RequestMapping.class).value();
                map.put(uri,clazz);
            }
        });
    }

    /**
     * 根据用户请求的uri从map获取相应的ControllerClass
     * @param request 根据请求地址进行匹配
     * @return
     */
    @Override
    public Object getHandler(HttpServletRequest request) {
        String uri = request.getRequestURI();
        //去掉contextPath的前缀
        uri = uri.replace(request.getContextPath(),"");
        return map.get(uri);
    }
}
